package org.millioncall.yueyoga.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.millioncall.openplatform.util.WebAppUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

/**
 * 自定义异常捕获器，添加了ajax异常处理。
 * 
 * @author zangjinyu
 * @version 1.0.0
 * 
 */
public class CustomSimpleMappingExceptionResolver extends
		SimpleMappingExceptionResolver {
	private static final Logger LOGGER = LoggerFactory
			.getLogger(CustomSimpleMappingExceptionResolver.class);

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		String viewName = determineViewName(ex, request);

		LOGGER.error("Controller捕获到异常", ex);// 将异常输出到日志中
		request.setAttribute(GlobalConstants.ERROR_EXCEPTION_CONTENT_KEY, ex);// 同时设置到Request属性中

		if (viewName != null) {

			if (WebAppUtils.isAjaxRequest(request)) {// 如果是ajax请求
				WebAppUtils.ajaxResponse(response, ex.getMessage());// 注意：ajax仅响应到前端最基本的异常信息，详细的在日志中进行输出
				return null;
			} else {// 正常请求
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null) {
					applyStatusCodeIfPossible(request, response, statusCode);
				}

				ModelAndView mv = getModelAndView(viewName, ex, request);
				// 注：此ModeAndView中的ModelMap已经包含了异常信息，是以"exception"为key，存储的是异常对象。

				String errorTitle = "错误";
				String errorMsg = "友情提示：数据错误或您的操作出现异常，请联系管理员或稍候重试";

				GlobalService.initBasicData(request, mv.getModelMap());
				mv.getModelMap().put("errorTitle", errorTitle);
				mv.getModelMap().put("errorMsg", errorMsg);
				mv.getModelMap().put("errorException",
						GlobalService.buildStringOfException(ex));
				return mv;
			}
		} else {
			return null;
		}
	}

}
